<textarea
  id="the-compose-box-input-{realm}"
  class="compose-box-input compose-box-input-realm-{realm}"
  placeholder="{intl.composeLabel}"
  aria-describedby="compose-box-input-description-{realm}"
  aria-owns="compose-autosuggest-list-{realm}"
  aria-expanded={autosuggestShownForThisInput}
  aria-autocomplete="both"
  aria-activedescendant={activeDescendant}
  ref:textarea
  bind:value=rawText
  on:focus="onFocus()"
  on:blur="onBlur()"
  on:selectionChange="onSelectionChange(event)"
  on:keydown="onKeydown(event)"
></textarea>
<label for="the-compose-box-input-{realm}" class="sr-only">
  {intl.composeLabel}
</label>
<span id="compose-box-input-description-{realm}" class="sr-only">
  {intl.autocompleteDescription}
</span>
<style>
  .compose-box-input {
    grid-area: input;
    margin: 10px 0 0 5px;
    padding: 10px;
    border: 1px solid var(--input-border);
    min-height: 75px;
    resize: none;
    overflow: hidden;
    word-wrap: break-word;
    /* Text must be at least 16px or else iOS Safari zooms in */
    font-size: 1.2em;
    /* Hack to make Edge stretch the element all the way to the right.
     * Also desktop Safari makes the gauge stretch too far to the right without it.
     */
    width: calc(100% - 5px);
  }

  .compose-box-input-realm-dialog {
    max-height: 40vh;
    overflow-y: auto;
  }

  @media (max-width: 767px) {
    .compose-box-input-realm-dialog {
      max-height: 30vh;
    }
  }

  @media (max-width: 479px) {
    .compose-box-input-realm-dialog {
      max-height: 20vh;
    }
  }
</style>
<script>
  import { store } from '../../_store/store.js'
  import { autosize } from '../../_thirdparty/autosize/autosize.js'
  import { scheduleIdleTask } from '../../_utils/scheduleIdleTask.js'
  import { mark, stop } from '../../_utils/marks.js'
  import { selectionChange } from '../../_utils/events.js'
  import {
    clickSelectedAutosuggestionUsername,
    clickSelectedAutosuggestionEmoji, clickSelectedAutosuggestionHashtag
  } from '../../_actions/autosuggest.js'
  import { observe } from 'svelte-extras'
  import { get } from '../../_utils/lodash-lite.js'
  import { on } from '../../_utils/eventBus.js'
  import { requestPostAnimationFrame } from '../../_utils/requestPostAnimationFrame.js'
  import { throttleTimer } from '../../_utils/throttleTimer.js'
  import { isWebKit } from '../../_utils/userAgent/isWebKit.js'

  const updateComposeTextInStore = throttleTimer(scheduleIdleTask)

  export default {
    oncreate () {
      this.setupSyncFromStore()
      this.setupSyncToStore()
      this.setupAutosize()
      this.setupResize()
      this.setCursorIfNecessary()
    },
    ondestroy () {
      this.teardownAutosize()
    },
    methods: {
      observe,
      setupSyncFromStore () {
        const textarea = this.refs.textarea
        let firstTime = true
        this.observe('text', text => {
          const { rawText } = this.get()
          if (rawText !== text) {
            let newSelectionStart
            if (!firstTime) {
              const { selectionStart, selectionEnd } = textarea
              if (selectionStart > 0 && selectionStart === selectionEnd) {
                // Preserve cursor position when doing an autosuggest.
                // Note that we don't need to do anything special to measure length here, because
                // the selectionStart value is not emoji-aware.
                newSelectionStart = (text.length - rawText.length) + selectionStart
              }
            }
            this.set({ rawText: text })
            if (typeof newSelectionStart === 'number' && newSelectionStart > 0) {
              textarea.selectionStart = textarea.selectionEnd = newSelectionStart
            }
            // this next autosize is required to resize after
            // the user clicks the "toot" button
            mark('autosize.update()')
            autosize.update(textarea)
            stop('autosize.update()')
          }
          if (firstTime) {
            firstTime = false
            const { autoFocus } = this.get()
            if (autoFocus) {
              const { realm } = this.get()
              if (realm === 'dialog') {
                // If we're in a dialog, the dialog will be hidden at this
                // point. Also, the dialog has its own initial focus behavior.
                // Tell the dialog to focus the textarea.
                textarea.setAttribute('autofocus', true)
              } else {
                requestAnimationFrame(() => textarea.focus({ preventScroll: true }))
              }
            }
          }
        })
      },
      setupSyncToStore () {
        const { realm } = this.get()
        this.observe('rawText', rawText => {
          updateComposeTextInStore(() => {
            mark('updateComposeTextInStore')
            this.store.setComposeData(realm, { text: rawText })
            this.store.save()
            stop('updateComposeTextInStore')
          })
        }, { init: false })
      },
      setupAutosize () {
        const textarea = this.refs.textarea
        requestPostAnimationFrame(() => {
          mark('autosize()')
          autosize(textarea)
          stop('autosize()')
        })
      },
      teardownAutosize () {
        mark('autosize.destroy()')
        autosize.destroy(this.refs.textarea)
        stop('autosize.destroy()')
      },
      onBlur () {
        requestAnimationFrame(() => {
          this.store.setForCurrentAutosuggest({ composeFocused: false })
        })
      },
      onFocus () {
        scheduleIdleTask(() => {
          const { realm } = this.get()
          this.store.set({ currentComposeRealm: realm })
          this.store.setForCurrentAutosuggest({ composeFocused: true })
        })
      },
      onSelectionChange (selectionStart) {
        scheduleIdleTask(() => {
          this.store.setForCurrentAutosuggest({ composeSelectionStart: selectionStart })
        })
      },
      onKeydown (e) {
        const { keyCode } = e
        // ctrl or cmd (on macs) was pressed; ctrl-enter means post a toot
        const ctrlPressed = e.getModifierState('Control') || e.getModifierState('Meta')
        switch (keyCode) {
          case 9: { // tab
            this.clickSelectedAutosuggestion(e)
            break
          }
          case 13: { // enter
            const autosuggestionClicked = this.clickSelectedAutosuggestion(e)
            if (!autosuggestionClicked && ctrlPressed) {
              this.fire('postAction')
            }
            break
          }
          case 38: { // up
            this.incrementAutosuggestSelected(-1, e)
            break
          }
          case 40: { // down
            this.incrementAutosuggestSelected(1, e)
            break
          }
          case 27: { // escape
            this.clearAutosuggestions(e)
            break
          }
          default:
        }
      },
      clickSelectedAutosuggestion (event) {
        const {
          autosuggestShown,
          autosuggestType
        } = this.store.get()
        if (!autosuggestShown) {
          return false
        }
        event.preventDefault()
        event.stopPropagation()

        const clickAutosuggestedItem = async () => {
          const { realm } = this.get()
          /* autosuggestSelecting prevents a flash of searched content */
          this.store.setForCurrentAutosuggest({ autosuggestSelecting: true })
          if (autosuggestType === 'account') {
            await clickSelectedAutosuggestionUsername(realm)
          } else if (autosuggestType === 'hashtag') {
            await clickSelectedAutosuggestionHashtag(realm)
          } else { // emoji
            await clickSelectedAutosuggestionEmoji(realm)
          }
          this.store.setForCurrentAutosuggest({ autosuggestSelecting: false })
        }

        /* no await */ clickAutosuggestedItem()
        return true
      },
      incrementAutosuggestSelected (increment, event) {
        let {
          autosuggestShown,
          autosuggestSelected,
          autosuggestSearchResults
        } = this.store.get()
        if (!autosuggestShown) {
          return
        }
        autosuggestSelected += increment
        if (autosuggestSelected >= 0) {
          autosuggestSelected = autosuggestSelected % autosuggestSearchResults.length
        } else {
          autosuggestSelected = autosuggestSearchResults.length + autosuggestSelected
        }
        this.store.setForCurrentAutosuggest({ autosuggestSelected })
        event.preventDefault()
        event.stopPropagation()
      },
      clearAutosuggestions (event) {
        const { autosuggestShown } = this.store.get()
        if (!autosuggestShown) {
          return
        }
        this.store.setForCurrentAutosuggest({
          autosuggestSearchResults: [],
          autosuggestSelected: 0
        })
        event.preventDefault()
        event.stopPropagation()
      },
      setupResize () {
        on('resizeComposeInput', this, realm => {
          if (realm === this.get().realm) {
            autosize.update(this.refs.textarea)
          }
        })
      },
      setCursorIfNecessary () {
        const { realm } = this.get()
        if (isWebKit() && realm !== 'dialog' && realm !== 'home') {
          // Place the cursor at the end of the textarea in replies if this is WebKit.
          // Works around a Safari/WebKit bug: https://github.com/nolanlawson/pinafore/issues/1921
          // We only do this for replies (not dialog/home) because for dialog/home we don't want to
          // also focus the textarea, which is a side effect of setting selectionStart.
          // Potentially we could run this logic for all browsers, but I don't want to deal with the potential
          // perf hit or bugs of running more code for browsers that don't need it.
          requestAnimationFrame(() => {
            this.refs.textarea.selectionStart = this.refs.textarea.value.length
          })
        }
      }
    },
    store: () => store,
    data: () => ({
      rawText: ''
    }),
    computed: {
      /* eslint-disable camelcase */
      composeFocused: ({ $autosuggestData_composeFocused, $currentInstance, realm }) => (
        get($autosuggestData_composeFocused, [$currentInstance, realm], false)
      ),

      autosuggestShownForThisInput: ({ $autosuggestShown, composeFocused }) => (
        !!($autosuggestShown && composeFocused)
      ),
      autosuggestSelected: ({ $autosuggestData_autosuggestSelected, $currentInstance, realm }) => (
        get($autosuggestData_autosuggestSelected, [$currentInstance, realm], 0)
      ),
      activeDescendant: ({ autosuggestSelected, autosuggestShownForThisInput, realm }) => (
        autosuggestShownForThisInput ? `compose-autosuggest-active-item-${realm}-${autosuggestSelected}` : undefined
      )
      /* eslint-enable camelcase */
    },
    events: {
      selectionChange
    }
  }
</script>
